package com.ungao.framework.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Cglib代理类
 * 代理对象
 *
 * @author vic-ungao
 */
public class CglibProxy implements ProxyFactory, MethodInterceptor {

    /**
     * 代理目标对象
     */
    protected Object target;

    @Override
    public <T> T getProxy(T target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public <T> T getProxy(Class<T> target) throws IllegalAccessException, InstantiationException {
        this.target = target.newInstance();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target);
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public <R, T extends R> R getProxy(Class<R> clazz, T target) {
        throw new RuntimeException("The method cannot be called!");
    }

    @Override
    public <R, T extends R> R getProxy(Class<R> clazz, Class<T> target) {
        throw new RuntimeException("The method cannot be called!");
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        return methodProxy.invoke(target, args);
    }
}
